#include "downloadwidget.h"
#include <qthread.h>
#include <qdebug.h>
#include <qstandardpaths.h>
#include <qdir.h>
#include <qfiledialog.h>
#include <qfileinfo.h>

const QString DownloadWidget::DEFAULT_SAVE_PATH = 
	QStandardPaths::standardLocations(QStandardPaths::MusicLocation)
	.value(0, QDir::homePath());

DownloadWidget::DownloadWidget(const KSongWebInfo* song,QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	m_savePath = DEFAULT_SAVE_PATH;
	m_downloadURL = song->getMp3URLStr();
	m_fileName = song->getMuiscName() + ".mp3";
	ui.m_info->setText(m_savePath);
	ui.progressBar->setValue(0);
	
	connect(ui.m_startBtn, &QPushButton::clicked, this, &DownloadWidget::onHandleStartBtnClciked);
	connect(ui.m_setPathBtn, &QPushButton::clicked, this, &DownloadWidget::onHandleSetBtnClicked);
}

DownloadWidget::~DownloadWidget()
{
	if (m_taskThread.isRunning())
	{
		m_taskThread.quit();
		m_taskThread.wait();
	}
}



void DownloadWidget::onHandleStartBtnClciked()
{
	qDebug() << "main thread id:" << QThread::currentThreadId();
	ui.m_startBtn->setEnabled(false);
	qDebug() << saveFileName();
	m_task = new DownloadThreadTask(saveFileName(),m_downloadURL);
	m_task->moveToThread(&m_taskThread);

	connect(&m_taskThread, &QThread::finished, m_task, &DownloadThreadTask::deleteLater);
	connect(this, &DownloadWidget::startTask, m_task, &DownloadThreadTask::onHandleTask);
	connect(m_task, &DownloadThreadTask::progressUpdated, this, &DownloadWidget::onHandleProgressUpdated);
	connect(m_task, &DownloadThreadTask::taskFinished, this, &DownloadWidget::onHandleFinished);

	qDebug() << "emit";
	m_taskThread.start();
	emit startTask();
}

void DownloadWidget::onHandleSetBtnClicked()
{
	QString filename = QFileDialog::getExistingDirectory(this, "save path", DEFAULT_SAVE_PATH);
	if (!filename.isNull()) 
	{
		m_savePath = filename;
		ui.m_info->setText(m_savePath);
	}
}

void DownloadWidget::onHandleProgressUpdated(int progress)
{
	ui.progressBar->setValue(progress);
}

void DownloadWidget::onHandleFinished()
{
	m_taskThread.quit();
	emit endTask();
}

QString DownloadWidget::saveFileName() 
{
	QString filePath = m_savePath + "/" + m_fileName.remove(QRegExp("\\s"));
	QFileInfo fi(filePath);
	QString baseName = fi.baseName();
	QString suffix = fi.suffix();

	if (fi.isFile()) 
	{
		int i = 1;
		baseName += '_';
		while (QFileInfo(m_savePath + "/" + baseName + QString::number(i) + "." + suffix).isFile()) {
			++i;
		}
		baseName += QString::number(i);
		filePath = m_savePath + "/" + baseName +"."+ suffix;
	}
	return filePath;
}
